package service

import (
	"fmt"
	corev1 "k8s.io/api/core/v1"
	"kubernate-server/conf"
	"net/http"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type PodService struct {
}

/*
*	获取pod的详情信息
 */
func (*PodService) GetPodDetail(ctx *gin.Context) {
	//var err = conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Get(ctx, ctx.Param("nameSpace"))
	podDetail, err := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Get(ctx, ctx.Param("podName"), metav1.GetOptions{})
	fmt.Println(ctx.Param("nameSpace"), ctx.Param("podName"))
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge":    "success",
		"name":      podDetail.Name,
		"namespace": podDetail.Namespace,
		"status":    podDetail.Status,
	})
}

/*
*	获取pod列表
 */
func (*PodService) GetPodList(ctx *gin.Context) {
	podList, err := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).List(ctx, metav1.ListOptions{})

	if err != nil {
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge":  "success",
		"podList": podList,
	})
}

/*
*	添加一个pod
 */
func (*PodService) CreatePod(ctx *gin.Context) {
	_, error := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Create(ctx, creatPodReq2K8s(ctx), metav1.CreateOptions{})
	if error != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge": "success",
	})
}

// 转换k8s数据结构
func creatPodReq2K8s(ctx *gin.Context) *corev1.Pod {
	return &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      ctx.Param("podName"),
			Namespace: ctx.Param("nameSpace"),
		},
		Spec: corev1.PodSpec{
			NodeSelector: nil,
			Affinity:     nil,
			Tolerations:  nil,
			Containers: []corev1.Container{
				{
					Name:  "example-container",
					Image: "nginx:1.15-alpine",
				},
			},
			Volumes:     nil,
			DNSConfig:   nil,
			HostAliases: nil,
		},
	}
}

/*
*	更新一个pod
 */
func (*PodService) UpdatePod(ctx *gin.Context) {
	newPodDetail, _ := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Get(ctx, ctx.Param("podName"), metav1.GetOptions{})
	newPodDetail.Annotations = map[string]string{
		"updated-by": "client-go",
	}

	podNS := conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace"))
	_, err02 := podNS.Update(ctx, newPodDetail, metav1.UpdateOptions{})
	if err02 != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge": "success",
	})
}

/*
*	删除Pod
 */
func (*PodService) DeletePod(ctx *gin.Context) {
	var err = conf.KuberConfigSet.CoreV1().Pods(ctx.Param("nameSpace")).Delete(ctx, ctx.Param("podName"), metav1.DeleteOptions{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge": "success",
	})
}
